﻿
Imports remotecall

Public Interface rcEmitter
    Function runjob(ByVal job As ijob) As eventComb
End Interface

Public MustInherit Class rcEmitter(Of CLIENT_T, OUTPUT_T)
    Implements rcEmitter
    Private ReadOnly client As CLIENT_T = Nothing

    Public Sub New(ByVal host As String,
                   ByVal port As Int32,
                   Optional ByVal holdtimeMs As Int64 = tcpTalk4.defaultHoldTimeMs,
                   Optional ByVal livetimeMs As Int64 = tcpTalk4.defaultLiveTimeMs)
        client = create_client(host, port, holdtimeMs, livetimeMs)
    End Sub

    Protected MustOverride Function create_client(
                                        ByVal host As String,
                                        ByVal port As Int32,
                                        Optional ByVal holdtimeMs As Int64 = tcpTalk4.defaultHoldTimeMs,
                                        Optional ByVal livetimeMs As Int64 = tcpTalk4.defaultLiveTimeMs) As CLIENT_T
    Protected MustOverride Function invoke(ByVal client As CLIENT_T,
                                           ByVal name As String,
                                           ByRef ec As eventComb,
                                           ByVal rtn As pointer(Of OUTPUT_T),
                                           ByVal job As ijob) As Boolean
    Protected MustOverride Function parse_output_valid(ByVal o As OUTPUT_T) As Boolean
    Protected MustOverride Function parse_output_ijob(ByVal o As OUTPUT_T, ByRef job As ijob) As Boolean

    Public Function runjob(ByVal job As ijob) As eventComb Implements rcEmitter.runjob
        If job Is Nothing Then
            Return eventComb.failed()
        Else
            Dim ec As eventComb = Nothing
            Dim rtn As pointer(Of OUTPUT_T) = Nothing
            rtn = New pointer(Of OUTPUT_T)()
            Return New eventComb(Function() As Boolean
                                     Return invoke(client, rcDetector.remotecallName.runjob, ec, rtn, job) AndAlso
                                            waitfor(ec) AndAlso
                                            goto_next()
                                 End Function,
                                 Function() As Boolean
                                     Dim j As ijob = Nothing
                                     Return ec.end_result() AndAlso
                                            parse_output_valid(+rtn) AndAlso
                                            parse_output_ijob(+rtn, j) AndAlso
                                            job.copy(j) AndAlso
                                            goto_end()
                                 End Function)
        End If
    End Function
End Class
